const fs = require('fs');
const {connectUrl, client} = require('../mqtt');
const path = require("path");
const moment = require('moment');

let tenantCode = "1188"
let levelId = "1798629937202163714"
let mHmId = "1871749078506909698"
let mHmName = "ld"
let windSourceBoatCode = "00"

const fileType = "txt"

let shipGPSTopic = `mobile/up/gps/${tenantCode}/${levelId}/${mHmId}`;
let shipSpeedTopic = `mobile/up/speed/${tenantCode}/${levelId}/${mHmId}`;
let shipDirTopic = `mobile/up/heading/${tenantCode}/${levelId}/${mHmId}`;
let shipYawTopic = `mobile/up/yaw/${tenantCode}/${levelId}/${mHmId}`;
let shipRolTopic = `mobile/up/rol/${tenantCode}/${levelId}/${mHmId}`;
let VMGTopic = `mobile/up/vmg/${tenantCode}/${levelId}/${mHmId}`;
let heartRateTopic = `mobile/up/heartrate/${tenantCode}/${levelId}/${mHmId}`;

let originalTopic = `mobile/up/original/${tenantCode}/${levelId}/${mHmId}`;

let envTopic = `gateway/env/wind/${tenantCode}/${windSourceBoatCode}`;

const subscribeTopics = [
    shipGPSTopic,
    shipSpeedTopic,
    shipDirTopic,
    shipYawTopic,
    shipRolTopic,
    VMGTopic,
    heartRateTopic,
    originalTopic,
    envTopic,
]

client.on('connect', () => {
    let filePath = path.join('data', mHmName, "original");
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath, {recursive: true});
        console.log(`${filePath}目录创建成功`)
    }
    filePath = path.join('data', mHmName, "compute");
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath, {recursive: true});
        console.log(`${filePath}目录创建成功`)
    }
    filePath = path.join('data', mHmName, "env");
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath, {recursive: true});
        console.log(`${filePath}目录创建成功`)
    }
    console.log(`mqtt客户端建立成功，服务端地址【${connectUrl}】`)
    client.subscribe(subscribeTopics, {qos: 2}, err => {
        if (!err) {
            console.log("mqtt客户端订阅成功", subscribeTopics)
        }
    })
})

client.on('message', (topic, message) => {
    const msg = message.toString();
    const split = topic.split("/")
    if (!msg) {
        console.warn("消息为空")
        return
    }
    let filePath
    let fileName
    if (topic.startsWith("gateway")) {
        fileName = `${windSourceBoatCode}.${fileType}`
        filePath = `data/${mHmName}/env`
    } else if (topic.startsWith("mobile")) {
        let fileShortName
        if (split[2] === 'original') {
            fileShortName = JSON.parse(msg).dataType;
            filePath = `data/${mHmName}/original`
        } else {
            fileShortName = split[2]
            filePath = `data/${mHmName}/compute`
        }
        fileName = `${fileShortName}.${fileType}`
    }
    if (filePath && fileName) {
        fs.appendFile(`${filePath}/${fileName}`, message + "\n", (err) => {
            if (err) {
                console.error('写入文件时出错:', err);
            } else {
                console.log(`${moment().format('YYYY-MM-DD HH:mm:ss.SSS')} => ${filePath}/${fileName} 数据已写入到文件!`);
            }
        })
    }
})
